package com.sysu.minsysu.weibo.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.sysu.minsysu.wdzj.MinSYSUMessageActivity;
import com.sysu.minsysu.weibo.data.OAuth;
import com.sysu.minsysu.weibo.utils.ConfigUtil;

/**
 * 展示AccessToken
 * 
 * 		1. 获取授权后成功后回调的URL并匹配出验证码
 *  		（网易无验证码不处理）
 *  	2.获取OAuth对象并设置验证码
 *  	3.获取accessToken
 *  
 *
 */
public class ShowAccessTokenAct extends Activity{
	
	private String category;
	private String oauth_verifier;
	private String accessToken;
	private String token;
	private String secret;
	private String userId;
	
	private final String LOGTAG = "ShowAccessTokenAct";
	@Override
    protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
//	    setContentView(R.layout.showaccesstoken_ui);
	    
	    Bundle bundle = new Bundle();
	    bundle = this.getIntent().getExtras();
	    category = bundle.getString("category");
	    
	    String url = getIntent().getStringExtra(ConfigUtil.OAUTH_VERIFIER_URL);
    	Uri uri = Uri.parse(url);
    	//匹配验证码
		oauth_verifier = uri.getQueryParameter("oauth_verifier");
		
		OAuth oAuth = OAuth.getInstance();
		oAuth.setOauthVerifier(oauth_verifier);
		accessToken = oAuth.getAccessToken();
		oAuth.setTokenAndSecret(accessToken);
		token = oAuth.getToken();
		secret = oAuth.getSecret();
		userId = oAuth.getUserId();
		
		savesharedPreferences();
		
		Toast.makeText(this, "同步成功", Toast.LENGTH_LONG).show();
		
		Intent intent = new Intent(ShowAccessTokenAct.this, WeiboMainAct.class);
		startActivity(intent);
		finish();
    }
	
	public static final int MODE = MODE_PRIVATE;
	public String PREFERENCE_NAME_SINA = "xinlang";
	public String PREFERENCE_NAME_QQ = "tengxun";
	
	private void savesharedPreferences(){
		if (category.equals("xinlang")) {
			Log.e("authorization success!", category);
	    	SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME_SINA, MODE);	    	
	        
			SharedPreferences.Editor editor = sharedPreferences.edit();
			editor.putString("category", category);
			editor.putString("userId", userId);
			editor.putString("oauth_token", token);
			editor.putString("oauth_token_secret", secret);
			Log.e(PREFERENCE_NAME_SINA, token);
			Log.e(PREFERENCE_NAME_SINA, secret);
			editor.commit();
		} else if (category.equals("tengxun")) {
			Log.e("authorization success!", category);
	    	SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME_QQ, MODE);	    	
	        
			SharedPreferences.Editor editor = sharedPreferences.edit();
			editor.putString("category", category);
			editor.putString("userId", userId);
			editor.putString("oauth_token", token);
			editor.putString("oauth_token_secret", secret);
			Log.e(PREFERENCE_NAME_QQ, token);
			Log.e(PREFERENCE_NAME_QQ, secret);
			editor.commit();
		}
	}
	
}
